package GUI;

import general.ActionEnum;
import general.FileUtils;
import general.GlobalProperties;
import jsonObjects.Attributes;
import jsonObjects.Profile;
import org.apache.log4j.Logger;

import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;

import systemFile.FileBuffer;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class FileAttributesEditGUI extends JFrame {
    private static Logger log = Logger.getLogger(FileAttributesEditGUI.class);

    public FileAttributesEditGUI(File file, Profile profile) {
	this.profile = profile;
	this.file = file;
	initComponents();
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
	try {
	    UIManager
		    .setLookAndFeel(new Plastic3DLookAndFeel());
	} catch (Exception e) {
	    log.error(e.getMessage());
	}
	cancelButton = new JButton();
	okButton = new JButton();
	jScrollPane1 = new JScrollPane();
	jTable1 = new JTable();

	setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
	setForeground(java.awt.Color.white);
	setName("frame");

	cancelButton.setText("Cancel");
	cancelButton.addActionListener(new java.awt.event.ActionListener() {
	    public void actionPerformed(java.awt.event.ActionEvent evt) {
		jButton1ActionPerformed(evt);
	    }
	});

	okButton.setText("Save");
	okButton.addMouseListener(new java.awt.event.MouseAdapter() {
	    public void mouseClicked(java.awt.event.MouseEvent evt) {
		jButton2MouseClicked(evt);
	    }
	});
	okButton.addActionListener(new java.awt.event.ActionListener() {
	    public void actionPerformed(java.awt.event.ActionEvent evt) {
		jButton2ActionPerformed(evt);
	    }
	});

	Map<Attributes, String> mapa = FileUtils.getAtrybutyPliku(
		file.getName(), profile);

	Object[][] futureMenuItems;
	if (mapa != null && !mapa.isEmpty()) {
	    int i = 0;
	    futureMenuItems = new Object[mapa.size()][2];

	    for (Attributes a : mapa.keySet()) {
		futureMenuItems[i][0] = a.getName();
		futureMenuItems[i][1] = mapa.get(a);
		i++;
	    }
	} else
	    futureMenuItems = new Object[0][0];

	jTable1.setModel(new DefaultTableModel(futureMenuItems, new String[] {
		"Nazwa", "Wartosc" }) {
	    Class[] types = new Class[] { String.class, String.class };
	    boolean[] canEdit = new boolean[] { false, true };

	    public Class getColumnClass(int columnIndex) {
		return types[columnIndex];
	    }

	    public boolean isCellEditable(int rowIndex, int columnIndex) {
		return canEdit[columnIndex];
	    }
	});
	jScrollPane1.setViewportView(jTable1);

	GroupLayout layout = new GroupLayout(getContentPane());
	getContentPane().setLayout(layout);
	layout.setHorizontalGroup(layout
		.createParallelGroup(GroupLayout.Alignment.LEADING)
		.addGroup(
			GroupLayout.Alignment.TRAILING,
			layout.createSequentialGroup()
				.addContainerGap()
				.addGroup(
					layout.createParallelGroup(
						GroupLayout.Alignment.TRAILING)
						.addComponent(
							jScrollPane1,
							GroupLayout.DEFAULT_SIZE,
							380, Short.MAX_VALUE)
						.addGroup(
							layout.createSequentialGroup()
								.addGap(0,
									0,
									Short.MAX_VALUE)
								.addComponent(
									cancelButton)
								.addPreferredGap(
									LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(
									okButton)))
				.addContainerGap()));
	layout.setVerticalGroup(layout.createParallelGroup(
		GroupLayout.Alignment.LEADING).addGroup(
		GroupLayout.Alignment.TRAILING,
		layout.createSequentialGroup()
			.addContainerGap()
			.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE,
				264, GroupLayout.PREFERRED_SIZE)
			.addPreferredGap(
				LayoutStyle.ComponentPlacement.RELATED,
				GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
			.addGroup(
				layout.createParallelGroup(
					GroupLayout.Alignment.BASELINE)
					.addComponent(cancelButton)
					.addComponent(okButton))
			.addContainerGap()));

	okButton.getAccessibleContext().setAccessibleName("okButton");

	pack();
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

	this.setVisible(false);
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
	this.setVisible(false);
    }

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
	Map<String, String> mapa = new HashMap<String, String>();
	for (int i = 0; i < jTable1.getRowCount(); i++) {
	    String a = String.valueOf(jTable1.getValueAt(i, 0));
	    String b = String.valueOf(jTable1.getValueAt(i, 1));
	    mapa.put(a, b);
	}

	FileOutputStream fos = null;
	try {
	    File propFile = FileUtils.getProfilePropertyFile(profile);
	    GlobalProperties.unhide(propFile);

	    fos = new FileOutputStream(propFile);
	    Properties properties = FileUtils.loadProperties(propFile);
	    String tmp;
	    for (String key : mapa.keySet()) {
		tmp = file.getName() + "?" + key;
		properties.setProperty(tmp, mapa.get(key));
	    }

	    properties.store(fos, "");

	    if (!propFile.isHidden())
		GlobalProperties.hide(propFile);
	} catch (Exception e) {
	    log.error(e.getMessage());
	} finally {
	    try {
		if (fos != null)
		    fos.close();
	    } catch (IOException e) {
		log.error(e.getMessage());
	    }
	}

	JOptionPane
		.showMessageDialog(null,
			"Niektore zmiany beda widoczne dopiero po ponownym uruchomieniu programu!");

	if (FileUtils.getProfilePropertyFile(profile).exists())
	    FileBuffer
		    .getInstance()
		    .getListOfFile()
		    .put(FileUtils.getProfilePropertyFile(profile),
			    ActionEnum.EDIT);

	this.setVisible(false);
    }

    JButton cancelButton;
    JButton okButton;
    JScrollPane jScrollPane1;
    JTable jTable1;
    File file;
    Profile profile;
}
